/*
 * @Descripttion: 人员
 * @version:
 * @Author: spring
 * @Date: 2022-04-16 22:58:51
 * @LastEditors: spring
 * @LastEditTime: 2022-04-18 22:25:53
 */
import React, { useContext, useState } from "react";
import * as actions from "../../useReducerStore/action/person";
import { AppContext } from "./";
import { mockRequest } from "../../apis/test"

export default function usePerson() {
  const ctx: any = useContext(AppContext);
  const sum = ctx.appState?.counts?.sum ?? 0
  const persons = ctx.appState?.persons || []
  interface Name {
    name: string;
  }
  // 定义接口
  interface Age {
    age: number;
  }
  const [name, setName] = useState<Name[]>([]);
  const [age, setAge] = useState<Age[]>([]);

  const addPerson = () => {
    ctx.dispatch(actions.addPerson({ ...name[0], ...age[0] }));
  };
  const savePersonState = (type: string) => (event: any) => {
    let { value } = event.target;
    type === "name" &&
      setName([
        {
          [type]: value,
        },
      ]);
    type === "age" &&
      setAge([
        {
          [type]: value,
        },
      ]);
  };
  const requestDemo = () => {
    mockRequest().then(res => {
      console.log(res)
    }).catch(err => {
      console.log(err)
    })
  }
  return (
    <div>
      <h1>person组件</h1>
      <h4>读取组件的和是：{sum}</h4>
      <input
        type="text"
        placeholder="name"
        onChange={savePersonState("name")}
      />
      <input type="text" placeholder="age" onChange={savePersonState("age")} />
      <button onClick={addPerson}>add</button>
      <button onClick={requestDemo}>模拟请求</button>
      <ul>
        {persons.map((item: { name: string; age: string }, index: number) => {
          return (
            <li key={index}>
              {item.name}---{item.age}
            </li>
          );
        })}
      </ul>
    </div>
  );
}
